//
//  RemotePushMoudel.swift
//  KaisafinStockSwift
//
//  Created by administrator on 2019/12/20.
//  Copyright © 2019 administrator. All rights reserved.
//

import Foundation
import UIKit
import UserNotifications
import PushKit


extension AppDelegate {
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceTokenStr = deviceToken.map{String(format:"%02.2hhx", arguments: [$0]) }.joined()
        
        print("设备token--- \(deviceTokenStr)")
        
        GeTuiSdk.registerDeviceTokenData(deviceToken)
       
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error){
        print(error)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]){
        GetuiBusiness.oneBusinessReceiveRemotePush(userInfo: userInfo)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        GeTuiSdk.handleRemoteNotification(userInfo);
        completionHandler(UIBackgroundFetchResult.newData);
        
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        GeTuiSdk.destroy()
    }
    
}

let kGtAppId:String = "KONpxA1i1g8KciYM8H7XL1"
let kGtAppKey:String = "nkDkLOhkDu6tgbtgLrwR94"
let kGtAppSecret:String = "AMz1Ho8jbN8oPzNJxxwQH3"
class GetuiModule : NSObject, ModuleManagerDelegate, UNUserNotificationCenterDelegate,GeTuiSdkDelegate {
    var delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?){

        GeTuiSdk.start(withAppId: kGtAppId, appKey: kGtAppKey, appSecret: kGtAppSecret, delegate: self);

        self.registerAppNotificationSettings(launchOptions: launchOptions)
    }
    
    func registerAppNotificationSettings(launchOptions: [UIApplication.LaunchOptionsKey : Any]?) {

        let notifiCenter = UNUserNotificationCenter.current()
        notifiCenter.delegate = self
        let types = UNAuthorizationOptions(arrayLiteral: [.alert, .badge, .sound])
        notifiCenter.requestAuthorization(options: types) { (flag, error) in
            if flag {
                print("iOS request notification success")
            }
        }
        
        UIApplication.shared.registerForRemoteNotifications()
        
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void){
        completionHandler([.badge,.sound,.alert]);
    }
    
    public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void){
        
        GeTuiSdk.handleRemoteNotification(response.notification.request.content.userInfo);
        GetuiBusiness.oneBusinessReceiveRemotePush(userInfo: response.notification.request.content.userInfo)
        completionHandler();
    }
    
    func setBadge(badge:Int) {
        UIApplication.shared.applicationIconBadgeNumber = -1
        GeTuiSdk.resetBadge()
    }
    
    
    //mark GeTuiSdkDelegate
    
    func geTuiSdkDidRegisterClient(_ clientId: String!) {
        print("clientId \(clientId ?? "")")
        let cid = BYUserDeaultMacro.readString(key: geTuiClientID)
        if cid.count == 0 && cid != clientId {
//            KSNetwork.sendRequest(target: MultiTarget(KSMineAPI.deviceGetuiRelation), showError: false, showNetworkError: false, success: { (response) in
//                if response?.success == true {
//                    print("clientId上传成功")
//                    ksUserDeaultMacro.saveString(value: clientId, key: geTuiClientID)
//                }
//            }) { (error) in
//
//            }
        }
        
    }
    
    func geTuiSDkDidNotifySdkState(_ aStatus: SdkStatus) {
        print("sdkStatus \(aStatus)")
    }
    
    func geTuiSdkDidReceivePayloadData(_ payloadData: Data!, andTaskId taskId: String!, andMsgId msgId: String!, andOffLine offLine: Bool, fromGtAppId appId: String!) {
        //透传
        var payloadMsg = "";
        if((payloadData) != nil) {
            payloadMsg = String.init(data: payloadData, encoding: String.Encoding.utf8)!;
        }
        
        let msg:String = "Receive Payload: \(payloadMsg), taskId:\(String(describing: taskId)), messageId:\(String(describing: msgId))"
        print("geTuiSdkDidReceivePayloadData " + msg)
        NotificationCenter.default.post(name: noti_receive, object: true)
        NotificationCenter.default.post(name: noti_user_noti_update, object: nil)
        if offLine {
            return
        }
        
        
    }
    
    func geTuiSdkDidSendMessage(_ messageId: String!, result: Int32) {
        let msg:String = "sendmessage=\(String(describing: messageId)),result=\(result)";
        print("geTuiSdkDidSendMessage " + msg)
    }
}
